﻿using System;
using System.IO;
using Commons.Collections;
using NVelocity;
using NVelocity.App;

namespace Syno.Core.Output
{
    public class NVelocityTemplates : INVelocityTemplates
    {
        private readonly VelocityEngine _velocity;
        private readonly VelocityContext _context;
        
        public NVelocityTemplates()
        {
            _velocity = new VelocityEngine();
            var props = new ExtendedProperties();
            _velocity.Init(props);
            _context = new VelocityContext();
            TemplateName = Guid.NewGuid().ToString();
        }

        protected string TemplateName { get; set; }

        public void AddContext(string id, object somewhere)
        {
            _context.Put(id, somewhere);
        }

        public void WriteTemplate(TextReader textReader,TextWriter writer)
        {
            WriteTemplate(textReader.ReadToEnd(), writer);
        }

        public void WriteTemplate(string template , TextWriter writer)
        {
            _velocity.Evaluate(_context, writer, "", template);
        }

        public string ToString(string template)
        {
            return TemplateString(template);
        }

        private string TemplateString(string template)
        {
            var stringWriter = new StringWriter();
            WriteTemplate(template, stringWriter);
            var templateString = stringWriter.ToString();
            if (templateString != template)
            {
                return TemplateString(templateString);
            }
            return templateString;
        }
    }
}